<?php

function add_data() {
	global $USER, $CFG;
	
	if(empty($USER->adminfeed_key)) {
		echo "Need a valid admin feedkey to continue";
		exit;
	}
	
	
	$data = $_POST['data'];
	
	$type = optional_param('type','default');
	switch ($type) {
	
	case "measurements":
	case "exercise":
	default:
	
	$single = optional_param('single_entry');
	$retid = optional_param('return_id');
	$ret = new stdClass();
	
	
	$xml = new SimpleXMLElement($data);
	$ids = "";
	$ids = $xml->omitsessions;
	
	if(begin_sql()) {
		foreach($xml->sessions->session  as $session) {

			$sessinfo = $session->sessioninfo;
			$sessdata = $session->sessiondata->datarecord;
			$sessdaily = $session->sessiondaily;
			$sessdiet = $session->sessiondiet;
			
			$sessinfo->user = $USER->id;
			$sessdaily->user = $USER->id;
			$sessdiet->user = $USER->id;
			
			if(!empty($sessinfo)) {
				if(!record_exists('mercurius_exercise_log','date',$sessinfo->date,'duration',$sessinfo->duration,'user',$sessinfo->user)) {
					$ret = get_record('mercurius_exercise_log','date',$sessinfo->date,'duration',$sessinfo->duration,'user',$sessinfo->user,'id');
					 clean_exercise_log($sessinfo);
					 
					 if(empty($sessinfo->hr_max)) {
					 	$sessinfo->hr_max = getHRMax();
					 }
					 if(empty($sessinfo->vo2_max)) {
					 	$sessinfo->vo2_max = getVo2Max();
					 }
					 
					 $ret->id = insert_record('mercurius_exercise_log', $sessinfo, true);
					
					if($single == 'true' and $retid == 'true') {
						echo "OK:".$ret->id;
						exit;
					}
					
					$sql = "INSERT INTO {$CFG->prefix}mercurius_exercise_data ( ".
								"`session_prkey` ,`cum_duration` ,`hr` ,`speed` ,`cum_distance` , " .
								"`lat` ,`lon` ,`altitude` ,`Data_type` ,`ACQStatus` ,`TrueHeading` ,`MagHeading`) ".
								"VALUES ";
					$postfirst = false;
					$count  = 0;
					foreach($sessdata as $dataid => $datarecord) {
						if($postfirst) {
							$sql .= ", ";
						}
						
						if(!isset($datarecord->ACQStatus)) {
							$datarecord->ACQStatus = "NULL";
						}
						
						if(!isset($datarecord->TrueHeading)) {
							$datarecord->TrueHeading = "NULL";
						}
						
						if(!isset($datarecord->MagHeading)) {
							$datarecord->MagHeading = "NULL";
						}
						
						$datarecord->session_prkey = $ret->id;
						
						$sql .= "({$datarecord->session_prkey}," .
								"{$datarecord->cum_duration}," .
								"{$datarecord->hr}," .
								"{$datarecord->speed}," .
								"{$datarecord->cum_distance}," .
								"{$datarecord->lat}," .
								"{$datarecord->lon}," .
								"{$datarecord->altitude}," .
								"{$datarecord->Data_type}," .
								"{$datarecord->ACQStatus}," .
								"{$datarecord->TrueHeading}," .
								"{$datarecord->MagHeading}" .
								")";
						$postfirst = true;
					}
					
					execute_sql($sql,false);
				} else {
					echo "Exercise entry already exists";
					exit;
				}
			}
			if(!empty($sessdaily)) {
				if(!record_exists('mercurius_measurement_log','date',$sessdaily->date,'weight',$sessdaily->weight,'user',$sessdaily->user)) {
					if($sessdaily->weight > 0) {
						$newweightid = insert_record('mercurius_measurement_log',$sessdaily);
						if($single == 'true' and $retid == 'true') {
							echo "OK:".$newweightid;
							exit;
						}
					}
				} else {
					echo "Measurement entry already exists";
					exit;
				}
			}
			
			
			if(!empty($sessdiet)) {
				$diettype = required_param('diettype');
				$diettable = "";
				if($diettype == 'log') {
					$diettable = 'mercurius_nutrition_log';
				} else if($diettype == 'masterrep' or $diettype == 'privaterep') {
					$diettable = 'mercurius_nutrition_repository';
				}
			
			
				
				if(!record_exists($diettype,'user',$sessdiet->user,'name',$sessdiet->name) or $diettype == 'log') {
					if($sessdiet->nutrition > 0 and $sessdiet->servings > 0) {
						$newdiettid = insert_record($diettable,$sessdiet);
						if($single == 'true' and $retid == 'true') {
							echo "OK:".$newdiettid;
							exit;
						}
					}
				} else {
					echo "Diet entry already exists";
					exit;
				}
			}
			
			if(strlen($ids) > 0 and isset($ret->id) and $ret->id) {
				$ids .= ", " . $ret->id;
			} else if(strlen($ids) == 0 and is_numeric($ret->id)) {
				$ids .= $ret->id;
			}
		}
		
		$select = "";
		if(strlen($ids) > 0) {
			$select = 'id not in(' . $ids . ')';
		}
		
		if(commit_sql()) {
			echo "Result: Successful";
		} else {
			echo "Could not commit";
		}
	} else {
		echo "switch to transaction mode";
	}
	
	break;
	}
}

function update_data() {
	global $USER, $CFG;
	
	
	if(empty($USER->adminfeed_key)) {
		global $usersettings;
			
		if(count($usersettings) != 1) {  // User is already set, but did not provide a valid key.
			echo "Need a valid admin feedkey to continue";
			exit;
		}
	}
	
	$data = $_POST['data'];
	$type = required_param('type');
	switch ($type) {
	
	case "user":
	
	$xml = new SimpleXMLElement($data);
	$user = $xml->sessions->session->user;
	
	if($user->feed_key == '1') {
		$user->feed_key = uuid();
	} else {
		$user->feed_key = $USER->feed_key;
		$key = (string) $user->feed_key;
		if(empty($key)) {
			echo "Feedkey was not provided";
			exit;
		}
	}
	
	if($user->adminfeed_key == '1') {
		$user->adminfeed_key = uuid();
	} else {
		$user->adminfeed_key = $USER->adminfeed_key;
		$key = (string) $user->adminfeed_key;
		if(empty($key)) {
			echo "Admin Feedkey was not provided";
			exit;
		}
	}
	
	 if(empty($user->hr_max)) {
	 	$user->hr_max = getHRMax($user);
	 }
	 
	 if(empty($user->vo2_max)) {
	 	$user->vo2_max = getVo2Max($user);
	 }
	
	$user->userid = $USER->id;
	$user->id = get_field('mercurius_user_settings','id','userid',$USER->id);
	
	if(record_exists('mercurius_user_settings','userid',$USER->id)) {
		if(update_record('mercurius_user_settings',$user)) {
			echo "OK:1";
			exit;
		}
	} else {
		$retid = insert_record('mercurius_user_settings', $user, true);
		if(is_numeric($retid) and $retid > 0) {
			echo "OK:1";
		} else {
			echo "Could not create new profile";
		}
	}
	
	break;
	
	case "diet":
	case "measurements":
	case "exercise":
	
	
	$single = optional_param('single_entry');
	
	$xml = new SimpleXMLElement($data);
	$ids = "";
	$ids = $xml->omitsessions;
	
	foreach($xml->sessions->session  as $session) {
		$sessinfo = $session->sessioninfo;
		$sessdata = $session->sessiondata->datarecord;
		$sessdaily = $session->sessiondaily;
		$sessdiet = $session->sessiondiet;
		
		$sessinfo->user = $USER->id;
		$sessdaily->user = $USER->id;
		$sessdiet->user = $USER->id;
		
		if(!empty($sessinfo)) {
			if(record_exists('mercurius_exercise_log','id',$sessinfo->id,'user',$sessinfo->user)) {
				clean_exercise_log($sessinfo);
				
				if(empty($sessinfo->hr_max)) {
				 	$sessinfo->hr_max = getHRMax();
				 }
				 if(empty($sessinfo->vo2_max)) {
				 	$sessinfo->vo2_max = getVo2Max();
				 }
				
				if(update_record('mercurius_exercise_log',$sessinfo) && $single == 'true') {
					echo "OK:1";
					exit;
				}
			} else {
				echo "Exercise entry {$sessinfo->id} does not exists";
				exit;
			}
		}
		if(!empty($sessdaily)) {
			if(record_exists('mercurius_measurement_log','id',$sessdaily->id,'user',$sessdaily->user)) {
				if(update_record('mercurius_measurement_log',$sessdaily) && $single == 'true') {
					echo "OK:1";
					exit;
				}
			} else {
				echo "Measurement entry {$sessdaily->id} does not exists";
				exit;
			}
		}
		
		if(!empty($sessdiet)) {
			$diettype = required_param('diettype');
			$diettable = "";
			if($diettype == 'log') {
				$diettable = 'mercurius_nutrition_log';
			} else if($diettype == 'masterrep' or $diettype == 'privaterep') {
				$diettable = 'mercurius_nutrition_repository';
			}
		
			if(record_exists($diettable,'id',$sessdiet->id,'user',$sessdiet->user)) {
				if(update_record($diettable,$sessdaily) && $single == 'true') {
					echo "OK:1";
					exit;
				}
			} else {
				echo "Diet entry {$sessdiet->id} does not exists";
				exit;
			}
		}
	}	
	
	break;
	}
}

function delete_data() {
	global $USER, $CFG;
	
	
	if(empty($USER->adminfeed_key)) {
		echo "Need a valid admin feedkey to continue";
		exit;
	}	
	
	$data = $_POST['data'];
	if(empty($data)) {
		echo "Data was not provided via POST";
		exit;
	}
	$type = required_param('type');
	$results = "";
	switch ($type) {
	

	case "diet":
	case "measurements":
	case "exercise":

	$single = optional_param('single_entry');
	$xml = new SimpleXMLElement($data);
	$ids = "";
	$ids = $xml->omitsessions;
	
	foreach($xml->sessions->session  as $session) {
		$sessinfo = $session->sessioninfo;
		$sessdata = $session->sessiondata->datarecord;
		$sessdaily = $session->sessiondaily;
		$sessdiet = $session->sessiondiet;
		
		$sessinfo->user = $USER->id;
		$sessdaily->user = $USER->id;
		$sessdiet->user = $USER->id;
		
		if(!empty($sessinfo)) {
			if(record_exists('mercurius_exercise_log','id',$sessinfo->id,'user',$sessinfo->user)) {
				delete_records('mercurius_exercise_log','id',$sessinfo->id,'user',$sessinfo->user);
				delete_records('mercurius_exercise_data','session_prkey',$sessinfo->id); 
				if($single == 'true') {
					echo "OK:1";
					exit;
				}
			} else {
				echo "Exercise entry {$sessinfo->id} does not exists";
				exit;
			}
		}

		if(!empty($sessdaily)) {
			if(record_exists('mercurius_measurement_log','id',$sessdaily->id,'user',$sessdaily->user)) {
				delete_records('mercurius_measurement_log','id',$sessdaily->id,'user',$sessdaily->user);
				if($single == 'true') {
					echo "OK:1";
					exit;
				}
			} else {
				echo "Measurement entry {$sessdaily->id} does not exists";
				exit;
			}
		}
		
		if(!empty($sessdiet)) {
			$diettype = required_param('diettype');
			$diettable = "";
			if($diettype == 'log') {
				$diettable = 'mercurius_nutrition_log';
			} else if($diettype == 'masterrep' or $diettype == 'privaterep') {
				$diettable = 'mercurius_nutrition_repository';
			}
		
			if(record_exists($diettable,'id',$sessdiet->id,'user',$sessdiet->user)) {
				delete_records($diettable,'id',$sessdiet->id,'user',$sessdiet->user);
				if($single == 'true') {
					echo "OK:1";
					exit;
				}
			} else {
				echo "Diet entry {$sessdiet->id} does not exists";
				exit;
			}
		}
	}
	
	break;
	}
	echo $results;
	
}

function select_count_data() {
	global $USER, $CFG;
	
	$count = 0;
	$type = required_param('type');
	
	switch ($type) {
	case "measurements":
		$count = count_records('mercurius_measurement_log','user',$USER->id);
	    break;
	case "exercise":
	    $count = count_records('mercurius_exercise_log','user',$USER->id);
	    break;
	case "diet":
	
		$diettype = optional_param('diettype');
		if($diettype == 'log') {
			$count = count_records('mercurius_nutrition_log','user',$USER->id);
		} else if($diettype == 'masterrep') {
			$adminid = get_field('user', 'id', 'username', 'admin');
			$count = count_records('mercurius_nutrition_repository','user',$adminid);
		} else if($diettype == 'privaterep') {
			$count = count_records('mercurius_nutrition_repository','user',$USER->id);
		}
	
	    
	    break;
	case "resistance":
	    echo "Not implemented yet";
		break;
		
	default:
    	echo "Type $type is not supported";
    	exit;
	}
	
	
	echo "OK:$count";
}

function select_one_data() {
	global $USER, $CFG;
	select_data();
}

function select_data() {
	global $USER, $CFG;
	
	$type = required_param('type');
	$offset = optional_param('offset');
	$limit = optional_param('limit');
	$orderByColumnName = optional_param('orderByColumnName');
	$orderByDirection = optional_param('orderByDirection','true');
	$date = optional_param('date');
	$id = optional_param('id');
	
	
	if(empty($orderByColumnName)) {
		$orderByColumnName = 'date';
	}
	
	$sort = "desc";
	if($orderByDirection == 'false') { // not the default
		$sort = "asc";
	}
	

	$value = "";
	switch ($type) {
	case "measurements":
			$results = "";
			if($date) {
				 $select = "user = {$USER->id} and date = '$date'";
				 $results =  get_records_select('mercurius_measurement_log', $select, '','*', $offset, $limit);
			} else if($id) {
				$select = "user = {$USER->id} and id = '$id'";
				 $results =  get_records_select('mercurius_measurement_log', $select, '','*', $offset, $limit);
			} else {
				$results = get_records('mercurius_measurement_log','user',$USER->id,"$orderByColumnName $sort",'*',$offset,$limit);
			}
			
			$value {"count"} = count_records('mercurius_measurement_log','user',$USER->id);
			$i = 1;
			
			if(empty($results)) {
				break;
			}
			
			foreach($results as $id => $measurement) {
				foreach($measurement as $key => $val) {
					if($val == null and ($key == 'notes' or $key == 'milestone')) {
						$val = " ";
					} else if($val == null ){
						$val = "0";
					}
					
					if($key != 'user') {
						$value {"data"}{$i}{$key} = $val ."";
					}
				}
				
				$i = $i + 1;
			}

	    break;
	case "exercise":
	    $results = "";
			if($date) {
				 $select = "user = {$USER->id} and date = '$date'";
				 $results =  get_records_select('mercurius_exercise_log', $select, '','*', $offset, $limit);
			} else if($id) {
				$select = "user = {$USER->id} and id = '$id'";
				 $results =  get_records_select('mercurius_exercise_log', $select, '','*', $offset, $limit);
			} else {
				$results = get_records('mercurius_exercise_log','user',$USER->id,"$orderByColumnName $sort",'*',$offset,$limit);
			}
			
			$value {"count"} = count_records('mercurius_exercise_log','user',$USER->id);
			$i = 1;
			
			if(empty($results)) {
				break;
			}
			
			$defaultunit = "";
			
			foreach($results as $id => $exercise) {
				foreach($exercise as $key => $val) {
					if($val == null and ($key == 'notes' or $key == 'milestone')) {
						$val = " ";
					} else if($val == null ){
						$val = "0";
					} else if($val == 'mi') {
						$val = "1";
					} else if($val == 'km') {
						$val = "2";
					} 
					
					if($key == 'distance_unit') {
						$defaultunit = $val;
					} else if($key == 'speed_unit' and empty($val)) {
						$val = $defaultunit;
					}
					
					if($key != 'user') {
						$value {"data"}{$i}{$key} = $val ."";
					}
				}
				
				$value {"data"}{$i}{"gps"} = "".has_map_sessions($id)."";
				$value {"data"}{$i}{"points"} = "".calculate_points($exercise) . "";
				$value {"data"}{$i}{"calories"} = "".calculate_calories($exercise) . "";
				$i = $i + 1;
			}
			

	    break;
	case "user":
		if(empty($USER->adminfeed_key)) {
			global $usersettings;
			
			if(count($usersettings) != 1) {  // User is already set, but did not provide a valid key.
				echo "Need a valid admin feedkey to continue";
				exit;
			} else {
				
				$USER->dob = date('Y-m-d',0);
				$USER->gender = "1";
				$USER->height = "0";
				$USER->height_unit = "cm";
				$USER->feed_key = "";
				$USER->adminfeed_key = "";
				
			}
		}
		$value {"count"} = "1";
		$value {"data"}{1}{"id"} = $USER->id;
		$value {"data"}{1}{"user"} = $USER->username;
		$value {"data"}{1}{"firstname"} = $USER->firstname;
		$value {"data"}{1}{"lastname"} = $USER->lastname;
		$value {"data"}{1}{"email"} = $USER->email;
		$value {"data"}{1}{"dob"} = $USER->dob;
		$value {"data"}{1}{"hr_max"} = getHRMax();
		$value {"data"}{1}{"vo2_max"} = getVo2Max();
		$value {"data"}{1}{"gender"} = $USER->gender;
		$value {"data"}{1}{"height"} = $USER->height;
		if($USER->height_unit == 'in') {
			$value {"data"}{1}{"height_unit"} = "1";
		} else if($USER->height_unit == 'cm') {
			$value {"data"}{1}{"height_unit"} = "2";
		}
		
		$value {"data"}{1}{"feedkey"} = $USER->feed_key;
		$value {"data"}{1}{"adminfeedkey"} = $USER->adminfeed_key;
		
	    break;
	    
	case "summary":
		
		$wdaystart = get_user_preferences('calendar_startwday', CALENDAR_STARTING_WEEKDAY);
		$today=getdate();
		$twdiff = $today['wday'] - $wdaystart;
		if($today['wday'] < $wdaystart) {
			$twdiff = 7 - abs($twdiff);
		}

   		//This Week//
   		$start=$today[0]-(86400*($twdiff));
   		$end = $today[0];
	   
	    $twstart=date('Y-m-d',$start);
	    $twend=date('Y-m-d',$end);

	    
	    // Last Week
	    $lwend = $start - 86400;
	    $lwstart = $lwend - (86400* 6 );
	    
	    $lwstart=date('Y-m-d',$lwstart);
	    $lwend=date('Y-m-d',$lwend);
   	
	  $this_stats = get_exercise_log_stats($twstart,$twend);
	  $last_stats = get_exercise_log_stats($lwstart,$lwend);

		$value {"count"} = "1";

		$value {"data"}{1}{"durationThis"} = seconds_to_time($this_stats->total_duration_seconds);
		$value {"data"}{1}{"zoneDurationThis"} = seconds_to_time($this_stats->total_zone_seconds);
		$value {"data"}{1}{"caloriesThis"} = "".calculate_calories($this_stats) . "";
		$value {"data"}{1}{"distanceThis"} = "N/A";
		$value {"data"}{1}{"activitiesThis"} = "N/A";
		$value {"data"}{1}{"totalpointsThis"} = "" . $this_stats->total_points . "";
		
		$value {"data"}{1}{"durationLast"} = seconds_to_time($last_stats->total_duration_seconds);
		$value {"data"}{1}{"zoneDurationLast"} = seconds_to_time($last_stats->total_zone_seconds);
		$value {"data"}{1}{"caloriesLast"} = "".calculate_calories($last_stats) . "";
		$value {"data"}{1}{"distanceLast"} = "N/A";
		$value {"data"}{1}{"activitiesLast"} = "N/A";
		$value {"data"}{1}{"totalpointsLast"} = "" . $last_stats->total_points . "";

		$value {"data"}{1}{"z1This"} = $this_stats->z1_time. " / " . $this_stats->z1_points . " pts". " / " . calculate_zone_calories($this_stats,1) . " kcal";
		$value {"data"}{1}{"z2This"} = $this_stats->z2_time. " / " . $this_stats->z2_points . " pts". " / " . calculate_zone_calories($this_stats,2) . " kcal";
		$value {"data"}{1}{"z3This"} = $this_stats->z3_time. " / " . $this_stats->z3_points . " pts". " / " . calculate_zone_calories($this_stats,3) . " kcal";
		$value {"data"}{1}{"z4This"} = $this_stats->z4_time. " / " . $this_stats->z4_points . " pts". " / " . calculate_zone_calories($this_stats,4) . " kcal";
		$value {"data"}{1}{"z5This"} = $this_stats->z5_time. " / " . $this_stats->z5_points . " pts". " / " . calculate_zone_calories($this_stats,5) . " kcal";
		
		$value {"data"}{1}{"z1Last"} = $last_stats->z1_time. " / " . $last_stats->z1_points . " pts". " / " . calculate_zone_calories($last_stats,1) . " kcal";
		$value {"data"}{1}{"z2Last"} = $last_stats->z2_time. " / " . $last_stats->z2_points . " pts". " / " . calculate_zone_calories($last_stats,2) . " kcal";
		$value {"data"}{1}{"z3Last"} = $last_stats->z3_time. " / " . $last_stats->z3_points . " pts". " / " . calculate_zone_calories($last_stats,3) . " kcal";
		$value {"data"}{1}{"z4Last"} = $last_stats->z4_time. " / " . $last_stats->z4_points . " pts". " / " . calculate_zone_calories($last_stats,4) . " kcal";
		$value {"data"}{1}{"z5Last"} = $last_stats->z5_time. " / " . $last_stats->z5_points . " pts". " / " . calculate_zone_calories($last_stats,5) . " kcal";
		
	    break;
	case "diet":
	
	$diettype = optional_param('diettype');
	
	    $results = "";
	    $sql = "";
		$table = "";
		
		if($orderByColumnName == 'date' and ($diettype == 'privaterep' or $diettype == 'masterrep')) { // the default for others
			$orderByColumnName = 'name';
			$sort = 'asc';
		}
		// mercurius_nutrition_repository columns to show
		$rep_columns = "rep.id as nutritionid, rep.name, " .
		// "rep.templateid, " .
		"rep.pdv_kcalories, rep.serving_size, rep.amount, rep.amount_measurement," .
		"rep.kcalories, rep.fat_total, rep.fat_saturated, rep.fat_trans, rep.fat_polyunsaturated, rep.fat_monounsaturated, rep.cholesterol," .
		"rep.sodium, rep.potassium, rep.carb_total, rep.carb_fiber_dietary, rep.carb_fiber_soluble, rep.carb_fiber_insoluble, rep.carb_sugar,".
		"rep.carb_other, rep.protein, rep.Vitamin_A_retinol, rep.Vitamin_B1_thiamine, rep.Vitamin_B2_riboflavin, rep.Vitamin_B3_niacin, ".
		"rep.Vitamin_B5_pantothenic, rep.Vitamin_B6_pyridoxine, rep.Vitamin_B7_biotin, rep.Vitamin_B9_folic, rep.Vitamin_B12_cyanocobalamin, ".
		"rep.Vitamin_choline, rep.Vitamin_C_scorbic, rep.Vitamin_D_calciferol, rep.Vitamin_E_tocopherol, rep.Vitamin_K_naphthoquinone, ".
		"rep.Mineral_Cr_chromium, rep.Mineral_Br_Bromine, rep.Mineral_Co_Cobalt, rep.Mineral_Cu_Copper, rep.Mineral_Ge_Germanium, rep.Mineral_I_Iodine, ".
		"rep.Mineral_Fe_Iron, rep.Mineral_Mg_Magnesium, rep.Mineral_Mn_Manganese, rep.Mineral_Mo_Molybdenum, rep.Mineral_Se_Selenium,".
		"rep.Mineral_Zn_Zinc, rep.Mineral_Ca_Calcium, rep.Mineral_P_Phosphorus, rep.Mineral_S_Sulfur, rep.Mineral_V_Vanadium, rep.notes as nutrition_notes ";
		
		// mercurius_nutrition_log columns to show
		$log_columns = "log.id as id,log.date,log.time,log.servings,log.notes as log_notes";
		
		
		if($diettype == 'log') {
			
			$presql = " FROM {$CFG->prefix}mercurius_nutrition_log log " . "" .
			" JOIN {$CFG->prefix}mercurius_nutrition_repository rep ON rep.id = log.nutrition " .
			" WHERE log.user = {$USER->id} and rep.user = {$USER->id} ";
			
			if($date) {
				 $presql .= "and date = '$date'";
				 $sql = "SELECT $log_columns,$rep_columns $presql";
				 $results =  get_records_sql($sql);
			} else if($id) {
				$presql .= "and log.id = '$id'";
				$sql = "SELECT $log_columns,$rep_columns $presql";
				 $results =  get_records_sql($sql);
			} else {
				$sql = "SELECT $log_columns,$rep_columns $presql ORDER BY $orderByColumnName $sort";
				$results = get_records_sql($sql);
			}
			$results = get_records_sql($sql,$offset,$limit);
			$value {"count"} = count_records_sql("SELECT COUNT(*) $presql");
		
			
		} else if($diettype == 'masterrep') {
			$adminid = get_field('user', 'id', 'username', 'admin');
			if($id) {
				$select = "user = $adminid and rep.id = '$id'";
				$results =  get_records_select('mercurius_nutrition_repository', $select, '','*', $offset, $limit);
				$value {"count"} = count_records('mercurius_nutrition_repository','user',$adminid,'id',$id);
			} else {
				$results = get_records('mercurius_nutrition_repository','user',$adminid,"$orderByColumnName $sort",'*',$offset,$limit);
				$value {"count"} = count_records('mercurius_nutrition_repository','user',$adminid);
			}

		} else if($diettype == 'privaterep') {
			if($id) {
				$select = "user = {$USER->id} and id = '$id'";
				$results =  get_records_select('mercurius_nutrition_repository', $select, '','*');
				$value {"count"} = count_records('mercurius_nutrition_repository','user',$USER->id,'id',$id);
			} else {
				$results = get_records('mercurius_nutrition_repository','user',$USER->id,"$orderByColumnName $sort",'*',$offset,$limit);
				$value {"count"} = count_records('mercurius_nutrition_repository','user',$USER->id);
			}
		}

			
			$i = 1;
			
			if(empty($results)) {
				break;
			}
			
			foreach($results as $id => $diet) {
				foreach($diet as $key => $val) {
					if($val == null and ($key == 'notes')) {
						$val = " ";
					} else if($val == null ){
						$val = "0";
					}
					
					if($key != 'user') {
						$value {"data"}{$i}{$key} = $val ."";
					}
				}
				
				$i = $i + 1;
			}
	    
	    
	    
	    break;
	    
	    
	case "resistance":
	    echo "Not implemented yet";
		break;
		
	default:
    	echo "Type $type is not supported";
    	exit;
	}

	
	echo json_encode($value);exit;
}

function viewTotalPointGraph($gadget=false) {
	global $USER, $CFG;

	if(!$gadget) {
		$gadget   = optional_param('module');
	}
	
	
	$sql = "select id,DATE_FORMAT(date,'%V') + 1 as week, " .
			"date, " .
			"DATE_FORMAT(date,'%Y') as year, " .
			"DATE_FORMAT(date,'%b') as month, " .
	"ROUND(( " .
	"SUM(TIME_TO_SEC(z1_time)) * 1 * (1/60.0)  + " .
	"SUM(TIME_TO_SEC(z2_time)) * 2 * (1/60.0)  + " .
	"SUM(TIME_TO_SEC(z3_time)) * 3 * (1/60.0)  + " .
	"SUM(TIME_TO_SEC(z4_time)) * 4 * (1/60.0)  + " .
	"SUM(TIME_TO_SEC(z5_time)) * 5 * (1/60.0) " .
	")) as total_points " .
	"from {$CFG->prefix}mercurius_exercise_log " .
	"WHERE user={$USER->id} " .
	"GROUP BY week,year ORDER BY date ";

	$records = get_records_sql($sql);

	$seriesdata = "";
	$data = "";

	foreach($records as $index => $row) {
		
			// TODO: Should implement a way to include empty weeks since right now they get ignored.
			
			$seriesdata .= createValue($index,"{$row->month} {$row->year} (Wk {$row->week})");
			$data .= createValue($index,$row->total_points);
	}
	

	$title = "Total Points per Week";
	$htmlwrap=optional_param('fulldisplay');
	$settings = getDefaultGraphSettings();
	$settings->unit = " pts";
	$chart = GenerateChart($title,$seriesdata,$data,$settings,false,$gadget,$htmlwrap);

	if($gadget and is_object($chart)) {
		echo json_encode($chart);
	} else {
		echo $chart;
	}

}


function generateHRGraph($ids="",$width=600,$height=600) {
	global $USER, $CFG;
	
	if(empty($ids)) {
		$ids   = required_param('id');
	}
	
	$mod   = optional_param('mod',10);
	
	$w = optional_param('width');
	$h = optional_param('height');
	if(!empty($w)) {
		$width = $w;
	}
	if(!empty($h)) {
		$height = $h;
	}

	$dataarray = array();
	$graphs_data = array();
	if(is_array($ids)) {
		foreach($ids as $index => $id) {
			$dataarray[] = generateHRData($id);
			$graphs_data = array_merge($graphs_data,array("Graph $index"=>""));
		}
		
	} else {
		$dataarray[] = generateHRData();
		$graphs_data = array_merge($graphs_data,array("Graph 0"=>""));
	}
	
	$seriesdata = "";
	$skip = 30;
	foreach($dataarray as $index => $exercise) {
		$data = $exercise->data;
		$i = 0;
		foreach($data as $exerciseindx => $hrdata) {
			if(($exerciseindx % $mod) == 0) {
				$seriesdata .= "<value xid='$exerciseindx'>" . seconds_to_time(number_format($hrdata->cum_duration,0,'','')) . "</value>";
				$graphs_data["Graph $index"] .= createValue($exerciseindx,$hrdata->hr);
			}
		}
	}
	
	$title = "HR Graph";
	$htmlwrap =optional_param('fulldisplay');
	$settings = getDefaultGraphSettings();
	$settings->unit = " bpm";
	$gadget = false;
	$chart = GenerateChart($title,$seriesdata,$graphs_data,$settings,false,$gadget,$htmlwrap);

	if($gadget and is_object($chart)) {
		echo json_encode($chart);
	} else {
		echo $chart;
	}
	
	
	
	
	include_once($CFG->dirroot . '/mercurius/gmaps/map.html');
}


function viewMeasurementGraph() {

	global $USER, $CFG;
	// Defaults
	$showweight=optional_param('showweight',true);
	$showfatpercent=optional_param('showfatpercentage',false);
	$showfatmass=optional_param('showfatmass',false);
	$showlean=optional_param('showlean',false);
	$showbmi=optional_param('showbmi',false);
	$showbmr=optional_param('showbmr',false);
	$showrestingpulse=optional_param('showrestingpulse',false);
	$displaymilestone=optional_param('displaymilestone',true);
	
	$gadget=optional_param('module',false);

	$records = get_records('mercurius_measurement_log','user',$USER->id,'date asc');
	
	$seriesdata = "";
	$graphs_data = array('Weight'=>'','Fat Percent'=>'','Lean Mass'=>'','Fat Mass'=>'','BMI'=>'','BMR'=>'','Resting Pulse'=>'','W2'=>'');

	
	foreach($records as $index => $weight) {
		$lean = 0;
		$weight->milestone = trim($weight->milestone);
		$milestone = "";
		if(!empty($weight->milestone) and $displaymilestone) {
			$milestone = " -- " . $weight->milestone;
		}
		if($weight->fat > 0) {
			if($showrestingpulse == 'true') {
				$graphs_data['Resting Pulse'] .= createValue($index,$weight->restingpulse,$milestone);
			}
		}
		
		if($weight->fat > 0) {
			$fatmass = $weight->weight * ($weight->fat / 100.0);
			$lean = number_format($weight->weight - $fatmass,2, '.', '');
			$fatmass = number_format($fatmass,2,'.','');
			if($showlean == 'true') {
				$graphs_data['Lean Mass'] .= createValue($index,$lean,$milestone);
			}
			
			
			if($showfatpercent == 'true') {
				$graphs_data['Fat Percent'] .= createValue($index,$weight->fat,$milestone);
			}
			
			if($showfatmass == 'true') {
				$graphs_data['Fat Mass'] .= createValue($index,$fatmass,$milestone);
			}
		}
		
			$weight->date = date("M j, Y", strtotime($weight->date));
			$seriesdata .= "<value xid='$index' description='{$milestone}'>{$weight->date}</value>";
			if($showweight == 'true') {
				$graphs_data['Weight'] .= createValue($index,number_format($weight->weight,2, '.', ''),$milestone);
			}
			$weightmetric = 0;
			$heightmetric = 0;
			
			if($weight->weight_unit == 'lbs') {
				$weightmetric = $weight->weight * 0.45359237;
			} else {
				$weightmetric = $weight->weight;
			}
			
			if($USER->height_unit == 'in') {
				$heightmetric = $USER->height * 0.0254;
			} else {
				$heightmetric = $USER->height;
			}

			$bmi = ($weightmetric / ($heightmetric * $heightmetric));
			$bmr = 0;
			
			// Harris and Benedict equation for calculating BMR
			if($USER->gender == 1) { // male
				$bmr = 66.4730 + (13.7516 * $weightmetric)+(5.0033 * $heightmetric * 100)-(6.7550 * $USER->age);
			} else { // female
				$bmr = 655.0955+(9.5634 * $weightmetric)+(1.8496 * $heightmetric * 100)-(4.6756 * $USER->age);
			} 
			
			
			if($showbmi == 'true') {
				$graphs_data['BMI'] .= createValue($index,number_format($bmi,2, '.', ''),$milestone);
			}
			
			if($showbmr == 'true') {
				$graphs_data['BMR'] .= createValue($index,number_format($bmr,2, '.', ''),$milestone);
			}
	}
	
	$title = "Measurement History";
	$htmlwrap=optional_param('fulldisplay');
	
	$chart = GenerateChart($title,$seriesdata,$graphs_data,'',true,$gadget,$htmlwrap);

	if($gadget and is_object($chart)) {
		echo json_encode($chart);
	} else {
		echo $chart;
	}
}

function viewZonePointsGraph($z1=true,$z2=true,$z3=true,$z4=true,$z5=true,$gadget=false) {
	
		global $USER, $CFG;

	if(!$gadget) {
		$gadget   = optional_param('module');
	}

	$sql = "select id,date," .
	"DATE_FORMAT(date,'%V') + 1 as week, " .
	"DATE_FORMAT(date,'%Y') as year, " .
	"DATE_FORMAT(date,'%b') as month, " .
	"ROUND(SUM(TIME_TO_SEC(z1_time)) * 1 * (1/60.0)) as z1_points,  " .
	"ROUND(SUM(TIME_TO_SEC(z2_time)) * 2 * (1/60.0)) as z2_points,  " .
	"ROUND(SUM(TIME_TO_SEC(z3_time)) * 3 * (1/60.0)) as z3_points,  " .
	"ROUND(SUM(TIME_TO_SEC(z4_time)) * 4 * (1/60.0)) as z4_points,  " .
	"ROUND(SUM(TIME_TO_SEC(z5_time)) * 5 * (1/60.0)) as z5_points " .
	"from {$CFG->prefix}mercurius_exercise_log " .
	"WHERE user={$USER->id} " .
	"GROUP BY week,year ORDER BY date ";


	$records = get_records_sql($sql);

	$seriesdata = "";
	$graphs_data = array('Z1'=>'','Z2'=>'','Z3'=>'','Z4'=>'','Z5'=>'');

	foreach($records as $index => $row) {
		$seriesdata .= "<value xid='$index'>{$row->month} {$row->year} (Wk {$row->week})</value>";
		$graphs_data['Z1'] .= createValue($index,$row->z1_points);
		$graphs_data['Z2'] .= createValue($index,$row->z2_points);
		$graphs_data['Z3'] .= createValue($index,$row->z3_points);
		$graphs_data['Z4'] .= createValue($index,$row->z4_points);
		$graphs_data['Z5'] .= createValue($index,$row->z5_points);
	}
	$title = "Zone Point History";
	$chart = GenerateChart($title,$seriesdata,$graphs_data);
	
	$htmlwrap =optional_param('fulldisplay');
	$settings = getDefaultGraphSettings();
	$settings->unit = " pts";
	$chart = GenerateChart($title,$seriesdata,$graphs_data,$settings,false,$gadget,$htmlwrap);

	if($gadget and is_object($chart)) {
		echo json_encode($chart);
	} else {
		echo $chart;
	}
}

function generateGMap($ids="",$width=600,$height=600) {
	global $USER, $CFG;
	
	if(empty($ids)) {
		$ids   = required_param('id');
	}
	
	$w = optional_param('width');
	$h = optional_param('height');
	if(!empty($w)) {
		$width = $w;
	}
	if(!empty($h)) {
		$height = $h;
	}

	$center = "";
	$data = array();
	if(is_array($ids)) {
		foreach($ids as $index => $id) {
			$data[] = generateMapData($id);
		}
		
		$map = generateMapData();	
		$center = $map->center;
	} else {
		$map = generateMapData();
		$data[] = $map;
		$center = $map->center;
	}
	
	include_once($CFG->dirroot . '/mercurius/gmaps/map.html');
}

function viewExercise($id="") {
	global $USER, $CFG;
	
	if(empty($id)) {
		$id   = required_param('id');
	}
	
	$log = get_record('mercurius_exercise_log','id',$id);
	clean_exercise_log($log);
	
	echo generate_content($log);
}

function mapFeed() {
	
	global $USER, $CFG;
	$records = get_map_sessions($USER);

	generate_exercise_feed($USER,'mapFeed','Mercurius GMap Feed',$records);
}

function gadgetFeed() {
	global $CFG;
	generate_gadget_feed();
}

function exerciseFeed() {
	global $USER, $CFG;
	
	$a = optional_param('asc','false');
	$sort = "";
	if($a == 'true') {
		$sort = "date ASC";
	} else {
		$sort = "date DESC";
	}
	$records = get_records('mercurius_exercise_log','user',$USER->id,$sort);
	generate_exercise_feed($USER,'exerciseFeed','Mercurius Exercise Feed',$records);
}

function editmoodleuser() {
	global $keyaccess,$USER, $CFG;
	
	if($keyaccess) {  // reset to user before using keyaccess
		require_logout();
	}
	
	header("Location: {$CFG->wwwroot}/user/edit.php?id={$USER->id}");
	die;
}

function my() {
	global $keyaccess,$USER, $CFG;

	if($keyaccess) {  // reset to user before using keyaccess
		require_logout();
	}
	
	header("Location: {$CFG->wwwroot}/my");
	die;
}

function viewGadgets() {
	echo "Not implemented yet";
}

?>
